package com.kedsoft.andaily.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.kedsoft.andaily.common.CommonList;
import com.kedsoft.andaily.common.CommonResult;
import com.kedsoft.andaily.common.MessageResult;
import com.kedsoft.andaily.entity.*;
import com.kedsoft.andaily.service.*;
import com.kedsoft.andaily.service.impl.JpushService;
import com.kedsoft.andaily.util.DateUtil;
import com.kedsoft.andaily.util.ExcelUtils;
import com.kedsoft.andaily.vo.ExcelDataVo;
import com.kedsoft.andaily.vo.PageVo;
import com.kedsoft.andaily.vo.Pagination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LGP
 * @since 2019-04-10
 */
@Controller
@RequestMapping("/task")
public class TaskController {
    @Autowired
    TaskService taskService;

    @Autowired
    CunsumerService cunsumerService;

    @Autowired
    LogsService logsService;

    @Autowired
    ParamService paramService;

    @Autowired
    TaskFileService taskFileService;

    @Autowired
    NormalService normalService;

    @Autowired
    JpushService jpushService;

    @Autowired
    BoardroomService boardroomService;

    @RequestMapping("index")
    public String index(){
        return "task/index";
    }

    @RequestMapping("xsindex")
    public String xsindex(){
        return "task/xsindex";
    }

    @RequestMapping(value = "list")
    @ResponseBody
    public PageVo<Task> getPageList(Pagination pagination, @RequestParam(required = false) String boardname,
                                    @RequestParam(required = false) String projectcode,
                                    @RequestParam(required = false) String factoryname,
                                    @RequestParam(required = false) String routername){
        EntityWrapper<Task> entityWrapper = new EntityWrapper<>();
        entityWrapper.like("boardname",boardname);
        entityWrapper.like("factoryname",factoryname);
        entityWrapper.like("routername",routername);
//        entityWrapper.in("tasktype",new Integer[]{90,20,10,30});
        entityWrapper.notIn("tasktype",new Integer[]{40,50,60,70,80});
        entityWrapper.lt("status",50);
        entityWrapper.orderBy("status",false);
        entityWrapper.orderBy("createtime", true);
        if(pagination.getOrder()!=null) {
            if (pagination.getOrder().toLowerCase().equals("asc")){
                entityWrapper.orderBy(pagination.getSort(), true);
            }else{
                entityWrapper.orderBy(pagination.getSort(), false);
            }
        }
        Page<Task> page = new Page<>(pagination.getPage()==null?1:pagination.getPage(),
                pagination.getRows()==null?20:pagination.getRows());

        taskService.selectPage(page,entityWrapper);
        PageVo<Task> pageVo = new PageVo<>(page.getRecords(),page.getTotal());
        return pageVo;
    }

    @RequestMapping(value = "xslist")
    @ResponseBody
    public PageVo<Task> getXsPageList(Pagination pagination, @RequestParam(required = false) String boardname,
                                    @RequestParam(required = false) String projectcode,
                                    @RequestParam(required = false) String factoryname,
                                    @RequestParam(required = false) String routername){
        EntityWrapper<Task> entityWrapper = new EntityWrapper<>();
        entityWrapper.like("boardname",boardname);
        entityWrapper.like("factoryname",factoryname);
        entityWrapper.like("routername",routername);
        entityWrapper.in("tasktype",new Integer[]{40,50,60,70,80});
        entityWrapper.lt("status",50);
        entityWrapper.orderBy("status",false);
        entityWrapper.orderBy("createtime", true);
        if(pagination.getOrder()!=null) {
            if (pagination.getOrder().toLowerCase().equals("asc")){
                entityWrapper.orderBy(pagination.getSort(), true);
            }else{
                entityWrapper.orderBy(pagination.getSort(), false);
            }
        }
        Page<Task> page = new Page<>(pagination.getPage()==null?1:pagination.getPage(),
                pagination.getRows()==null?20:pagination.getRows());

        taskService.selectPage(page,entityWrapper);
        PageVo<Task> pageVo = new PageVo<>(page.getRecords(),page.getTotal());
        return pageVo;
    }

//    @RequestMapping(value = "allTask")
//    @ResponseBody
//    public CommonList<Task> getAllTask(){
//        EntityWrapper<Task> entityWrapper = new EntityWrapper<>();
//        entityWrapper.lt("status",40);
//        List<Task> list = taskService.selectList(entityWrapper);
//        return CommonList.success(list);
//    }

    /**
     * 正在进行的任务
     * @return
     */
    @RequestMapping(value = "allTask")
    @ResponseBody
    public CommonList<Task> getAllTask(){
        EntityWrapper<Task> entityWrapper = new EntityWrapper<>();
        entityWrapper.lt("status",40);
        entityWrapper.gt("status",10);
        List<Task> list = taskService.selectList(entityWrapper);
        return CommonList.success(list);
    }

    @RequestMapping(value = "warnningIndex")
    public String warnningIndex(){
        return "task/warnningIndex";
    }
    /**
     * 超时的日常任务
     * @param pagination
     * @return
     */
    @RequestMapping(value = "warnningList")
    @ResponseBody
    public PageVo<Task> getWarnningList(Pagination pagination){
        EntityWrapper<Task> entityWrapper = new EntityWrapper<>();
        entityWrapper.in("tasktype",new Integer[]{40,50,60,70,80});
        entityWrapper.lt("status",40);
        entityWrapper.lt("createtime",DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        entityWrapper.isNull("stoptime");
        entityWrapper.orderBy("status",false);
        entityWrapper.orderBy("createtime", true);
        if(pagination.getOrder()!=null) {
            if (pagination.getOrder().toLowerCase().equals("asc")){
                entityWrapper.orderBy(pagination.getSort(), true);
            }else{
                entityWrapper.orderBy(pagination.getSort(), false);
            }
        }
        Page<Task> page = new Page<>(pagination.getPage()==null?1:pagination.getPage(),
                pagination.getRows()==null?20:pagination.getRows());

        taskService.selectPage(page,entityWrapper);
        PageVo<Task> pageVo = new PageVo<>(page.getRecords(),page.getTotal());
        return pageVo;
    }

    @RequestMapping("lsindex")
    public String lsIndex(){
        return "task/lsindex";
    }

    @RequestMapping(value = "lslist")
    @ResponseBody
    public PageVo<Task> getPageLsList(Pagination pagination, @RequestParam(required = false) String boardname,
                                      @RequestParam(required = false) String projectcode, @RequestParam(required = false) String factoryname,
                                      @RequestParam(required = false) String routername,@RequestParam(required = false) String starttime,
                                      @RequestParam(required = false) String endtime,@RequestParam(required = false) String tasktype){
        EntityWrapper<Task> entityWrapper = new EntityWrapper<>();
        entityWrapper.like("projectcode",projectcode);
        entityWrapper.like("factoryname",factoryname);
        entityWrapper.like("routername",routername);
        //运维类型
        if (tasktype != null && !"".equals(tasktype)) {
            entityWrapper.eq("tasktype",Integer.parseInt(tasktype));
        }
        //开始于当天0点结束于当天最后一秒
        if(starttime!=null && !starttime.equals("")){
            entityWrapper.gt("stoptime",starttime+" 00:00:01");
        }
        if(endtime!=null && !endtime.equals("")){
            entityWrapper.lt("stoptime", endtime+" 23:59:59");
        }
        entityWrapper.eq("status",50);
        entityWrapper.orderBy("stoptime",true);
        if(pagination.getOrder()!=null) {
            if (pagination.getOrder().toLowerCase().equals("asc")){
                entityWrapper.orderBy(pagination.getSort(), true);
            }else{
                entityWrapper.orderBy(pagination.getSort(), false);
            }
        }
        Page<Task> page = new Page<>(pagination.getPage()==null?1:pagination.getPage(),
                pagination.getRows()==null?20:pagination.getRows());

        taskService.selectPage(page,entityWrapper);
        PageVo<Task> pageVo = new PageVo<>(page.getRecords(),page.getTotal());
        return pageVo;
    }

    @RequestMapping(value = "wwcUpdate")
    @ResponseBody
    public MessageResult wwcUpdate(String ids, HttpServletRequest request){
        String[] id = ids.split(",");
        Integer[] idparam = new Integer[id.length];
        for (int i=0;i<id.length;i++) {
            idparam[i] = Integer.parseInt(id[i]);
        }
        EntityWrapper<Task> taskEntityWrapper = new EntityWrapper<>();
        taskEntityWrapper.in("id",idparam);
        taskEntityWrapper.lt("status",50);
        Task task = new Task();
        task.setStatus(60);
        taskService.update(task,taskEntityWrapper);
        return MessageResult.getSuccess("修改数据成功");
    }

    @RequestMapping("wwcindex")
    public String wwcIndex(){
        return "task/wwcindex";
    }

    @RequestMapping(value = "wwclist")
    @ResponseBody
    public PageVo<Task> getPageWwcList(Pagination pagination, @RequestParam(required = false) String boardname,
                                      @RequestParam(required = false) String projectcode, @RequestParam(required = false) String factoryname,
                                      @RequestParam(required = false) String routername,@RequestParam(required = false) String starttime,
                                      @RequestParam(required = false) String endtime){
        EntityWrapper<Task> entityWrapper = new EntityWrapper<>();
        entityWrapper.like("projectcode",projectcode);
        entityWrapper.like("factoryname",factoryname);
        entityWrapper.like("routername",routername);
        //开始于当天0点结束于当天最后一秒
        if(starttime!=null && !starttime.equals("")){
            entityWrapper.gt("stoptime",starttime+" 00:00:01");
        }
        if(endtime!=null && !endtime.equals("")){
            entityWrapper.lt("stoptime", endtime+" 23:59:59");
        }
        entityWrapper.eq("status",60);
        entityWrapper.orderBy("stoptime",true);
        if(pagination.getOrder()!=null) {
            if (pagination.getOrder().toLowerCase().equals("asc")){
                entityWrapper.orderBy(pagination.getSort(), true);
            }else{
                entityWrapper.orderBy(pagination.getSort(), false);
            }
        }
        Page<Task> page = new Page<>(pagination.getPage()==null?1:pagination.getPage(),
                pagination.getRows()==null?20:pagination.getRows());

        taskService.selectPage(page,entityWrapper);
        PageVo<Task> pageVo = new PageVo<>(page.getRecords(),page.getTotal());
        return pageVo;
    }

    /**
     * 未完成历史清单任务导出
     */
    @RequestMapping(value = "wwcListTaskExcel", method = RequestMethod.POST)
    public void wwcListTaskExcel(HttpServletResponse response, @RequestParam(required = false) String boardname,
                                @RequestParam(required = false) String projectcode, @RequestParam(required = false) String factoryname,
                                @RequestParam(required = false) String routername,@RequestParam(required = false) String starttime,
                                @RequestParam(required = false) String endtime){
        EntityWrapper<Task> entityWrapper = new EntityWrapper<>();
        entityWrapper.like("projectcode",projectcode);
        entityWrapper.like("factoryname",factoryname);
        entityWrapper.like("routername",routername);
        //开始于当天0点结束于当天最后一秒
        if(starttime!=null && !starttime.equals("")){
            entityWrapper.gt("stoptime",starttime+" 00:00:01");
        }
        if(endtime!=null && !endtime.equals("")){
            entityWrapper.lt("stoptime", endtime+" 23:59:59");
        }
        entityWrapper.eq("status",60);
        entityWrapper.orderBy("stoptime",true);
        List<Task> lsListTask = new ArrayList<>();
        lsListTask = taskService.selectList(entityWrapper);
        ExcelDataVo excelDataVo = new ExcelDataVo();
        excelDataVo.setName("历史任务清单(开始日期："+starttime+"结束日期："+endtime+")");
        List<String> titles = new ArrayList();
        titles.add("所属项目编码");
        titles.add("所属项目名称");
        titles.add("配电房名称");
        titles.add("所属单位名称");
        titles.add("单位负责人");
        titles.add("单位联系方式");
        titles.add("巡视单位");
        titles.add("执行人员");
        titles.add("完成时间");
        titles.add("任务类型");
        excelDataVo.setTitles(titles);
        List<List<Object>> rows = new ArrayList();
        for (int i=0;i<lsListTask.size();i++){
            Task bean = lsListTask.get(i);
            List<Object> row = new ArrayList();
            row.add(bean.getProjectcode());
            row.add(bean.getProjectname());
            row.add(bean.getBoardname());
            row.add(bean.getFactoryname());
            row.add(bean.getFactoryuser());
            row.add(bean.getFactoryphone());
            row.add(bean.getRoutername());
            row.add(bean.getCname());
            row.add(DateUtil.format(bean.getStoptime(),"yyyy-MM-dd HH:mm:ss"));
            row.add(bean.getTasktypestr());
            rows.add(row);
        }
        excelDataVo.setRows(rows);
        try{
            ExcelUtils.exportExcel(response,"未完成历史任务清单",excelDataVo);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }

    /**
     * 历史清单任务导出
     */
    @RequestMapping(value = "lsListTaskExcel", method = RequestMethod.POST)
    public void lsListTaskExcel(HttpServletResponse response, @RequestParam(required = false) String boardname,
                                @RequestParam(required = false) String projectcode, @RequestParam(required = false) String factoryname,
                                @RequestParam(required = false) String routername,@RequestParam(required = false) String starttime,
                                @RequestParam(required = false) String endtime){
        EntityWrapper<Task> entityWrapper = new EntityWrapper<>();
        entityWrapper.like("projectcode",projectcode);
        entityWrapper.like("factoryname",factoryname);
        entityWrapper.like("routername",routername);
        //开始于当天0点结束于当天最后一秒
        if(starttime!=null && !starttime.equals("")){
            entityWrapper.gt("stoptime",starttime+" 00:00:01");
        }
        if(endtime!=null && !endtime.equals("")){
            entityWrapper.lt("stoptime", endtime+" 23:59:59");
        }
        entityWrapper.eq("status",50);
        entityWrapper.orderBy("stoptime",true);
        List<Task> lsListTask = new ArrayList<>();
        lsListTask = taskService.selectList(entityWrapper);
        ExcelDataVo excelDataVo = new ExcelDataVo();
        excelDataVo.setName("历史任务清单(开始日期："+starttime+"结束日期："+endtime+")");
        List<String> titles = new ArrayList();
        titles.add("所属项目编码");
        titles.add("所属项目名称");
        titles.add("配电房名称");
        titles.add("所属单位名称");
        titles.add("单位负责人");
        titles.add("单位联系方式");
        titles.add("巡视单位");
        titles.add("执行人员");
        titles.add("完成时间");
        titles.add("任务类型");
        titles.add("任务评价");
        excelDataVo.setTitles(titles);
        List<List<Object>> rows = new ArrayList();
        for (int i=0;i<lsListTask.size();i++){
            Task bean = lsListTask.get(i);
            List<Object> row = new ArrayList();
            row.add(bean.getProjectcode());
            row.add(bean.getProjectname());
            row.add(bean.getBoardname());
            row.add(bean.getFactoryname());
            row.add(bean.getFactoryuser());
            row.add(bean.getFactoryphone());
            row.add(bean.getRoutername());
            row.add(bean.getCname());
            row.add(DateUtil.format(bean.getStoptime(),"yyyy-MM-dd HH:mm:ss"));
            row.add(bean.getTasktypestr());
            row.add(bean.getAssess());
            rows.add(row);
        }
        excelDataVo.setRows(rows);
        try{
            ExcelUtils.exportExcel(response,"历史任务清单",excelDataVo);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }

    @RequestMapping("form")
    public String form(){
        return "task/form";
    }

    @RequestMapping(value = "save")
    @ResponseBody
    public MessageResult save(Task param, HttpServletRequest request){
        User session = (User)request.getSession().getAttribute("loginUser");

        Integer cunsumerid = param.getCunsumerid();
        Cunsumer cunsumer = cunsumerService.selectById(cunsumerid);
        param.setCunsumername(cunsumer.getName());
        param.setCunsumermobile(cunsumer.getMobile());
        //默认执行人员
        param.setCid(cunsumerid);
        param.setCname(cunsumer.getName());
        param.setCmobile(cunsumer.getMobile());
        param.setCreatetime(new Date());
        //用于统计的开始时间
        param.setStarttime(param.getCreatetime());
        param.setStatus(10);

        //任务类型名称
        Param p = getParam(param.getTasktype());
        param.setTasktypestr(p.getTitle());
        //任务所属年月
        param.setTaskdate(DateUtil.format(new Date(),"yyyyMM"));

        taskService.insert(param);

        //查询最后一个任务,就是当前插入的任务
        EntityWrapper<Task> wrapper = new EntityWrapper<>();
        wrapper.orderBy("id",false);
        Task bean = taskService.selectOne(wrapper);

        String opvalue = "[("+bean.getId()+")"+bean.getBoardname()+"]:【"+p.getTitle()+"】任务 被"+session.getUsername()+"创建。";

        //推送到Android客户端
        Map<String, String> extrasMap = new HashMap<String, String>();
        String title = bean.getBoardname()+"("+p.getTitle()+")";
        String content = "任务："+title+"["+ DateUtil.format(bean.getCreatetime(),"yyyy年MM月dd日 HH时mm分ss秒")+"],联系人："+bean.getJbname()+"电话："+bean.getJbphone();
        jpushService.sendCustomPush(title,content,extrasMap,bean.getCunsumermobile());
        //创建日志
        Logs logs = new Logs(bean.getId(),bean.getBoardname(),opvalue,new Date(),session.getUsername());
        logsService.insert(logs);
        return MessageResult.getSuccess("添加数据成功");
    }

    @RequestMapping(value = "update")
    @ResponseBody
    public MessageResult update(Task param, HttpServletRequest request){
        User session = (User)request.getSession().getAttribute("loginUser");
        Integer cunsumerid = param.getCunsumerid();
        Cunsumer cunsumer = cunsumerService.selectById(cunsumerid);
        param.setCunsumername(cunsumer.getName());
        param.setCunsumermobile(cunsumer.getMobile());
        //默认执行人员
        param.setCid(cunsumerid);
        param.setCname(cunsumer.getName());
        param.setCmobile(cunsumer.getMobile());

        //任务类型名称
        Param p = getParam(param.getTasktype());
        param.setTasktypestr(p.getTitle());

        taskService.updateById(param);

        String opvalue = "[("+param.getId()+")"+param.getBoardname()+"]:【"+p.getTitle()+"】任务 被"+session.getUsername()+"修改。";
        //创建日志
        Logs logs = new Logs(param.getId(),param.getBoardname(),opvalue,new Date(),session.getUsername());
        logsService.insert(logs);
        return MessageResult.getSuccess("修改数据成功");
    }

    /**
     * 接单操作
     * @param param
     * @return
     */
    @RequestMapping(value = "getTask")
    @ResponseBody
    public MessageResult getTask(Task param){
        param.setGettime(new Date());
        param.setStatus(20);
        taskService.updateById(param);
        //查询任务
        Task bean = taskService.selectById(param.getId());
        logsSave(bean,"被","接单");
        return MessageResult.getSuccess("修改数据成功");
    }

    /**
     * 开始操作
     * @param param
     * @return
     */
    @RequestMapping(value = "startTask")
    @ResponseBody
    public MessageResult startTask(Task param){
        param.setOptime(new Date());
        param.setStatus(30);
        taskService.updateById(param);

        //查询任务
        Task bean = taskService.selectById(param.getId());
        logsSave(bean,"由","开始操作");
        return MessageResult.getSuccess("修改数据成功");
    }

    /**
     * 开始操作
     * @param param
     * @return
     */
    @RequestMapping(value = "stopTask")
    @ResponseBody
    public MessageResult stopTask(Task param){
        param.setStoptime(new Date());
        param.setStatus(40);
        taskService.updateById(param);
        Task bean = taskService.selectById(param.getId());
        logsSave(bean,"被","结单");
        return MessageResult.getSuccess("修改数据成功");
    }

    @RequestMapping(value = "delete")
    @ResponseBody
    public MessageResult delete(@RequestParam Integer ids){
        taskService.deleteById(ids);
        return MessageResult.getSuccess("数据已删除");
    }

    @RequestMapping(value = "remove")
    @ResponseBody
    public MessageResult deletes(@RequestParam String ids){
        String[] id = ids.split(",");
        for (String i: id) {
            Integer intId = Integer.parseInt(i);
            taskService.deleteById(intId);
        }
        return MessageResult.getSuccess("数据已删除");
    }

    @RequestMapping(value = "more")
    @ResponseBody
    public CommonResult<Task> taskMore(@RequestParam Integer id){
        Task task = taskService.selectById(id);
        return CommonResult.success(task);
    }

    @RequestMapping("search")
    public String search(){
        return "task/search";
    }

    @RequestMapping("lssearch")
    public String lssearch(){
        return "task/lssearch";
    }

    @RequestMapping("edit")
    public String edit(){
        return "task/edit";
    }

    @RequestMapping("map")
    public String map(){
        return "task/map";
    }

    @RequestMapping("star")
    public String star(){
        return "task/star";
    }

    @RequestMapping(value = "updateStar")
    @ResponseBody
    public MessageResult updateStar(@RequestParam Integer id,@RequestParam Integer star){
        Task bean = new Task();
        bean.setId(id);
        bean.setAssess(star);
        bean.setStatus(50);
        boolean b = taskService.updateById(bean);
        if(b){
            return MessageResult.getSuccess("评价成功");
        }else{
            return MessageResult.getError("500","评价失败");
        }
    }

    /**
     * 运维类型查询
     * @param tasktype
     * @return
     */
    private Param getParam(Integer tasktype){
        EntityWrapper<Param> query = new EntityWrapper<>();
        query.eq("groups","运维类型");
        query.eq("value",tasktype);
        Param p = paramService.selectOne(query);
        return p;
    }

    /**
     *
     * @param bean
     * @param opv 操作动词
     * @param opresult 操作结果
     */
    private void logsSave(Task bean,String opv, String opresult){
        //任务类型名称
        Param p = getParam(bean.getTasktype());
        String opvalue = "[("+bean.getId()+")"+bean.getBoardname()+"]:【"+p.getTitle()+"】任务 "+opv+bean.getCunsumername()+"("+bean.getCunsumermobile()+")"+opresult+"。";
        //创建日志
        Logs logs = new Logs(bean.getId(),bean.getBoardname(),opvalue,new Date(),bean.getCunsumername());
        logsService.insert(logs);
    }

    @RequestMapping(value = "files", method = RequestMethod.GET)
    @ResponseBody
    public CommonList<TaskFile> taskfiles(@RequestParam Integer taskid,@RequestParam Integer filetype){
        EntityWrapper<TaskFile> wrapper = new EntityWrapper<>();
        wrapper.eq("taskid",taskid);
        wrapper.eq("filetype",filetype);
        List<TaskFile> list = taskFileService.selectList(wrapper);
        return CommonList.success(list);
    }

    /**
     * 重新生成相关bardroom的任务。
     * @param boardid
     * @return
     */
    @RequestMapping(value = "reCreateTask", method = RequestMethod.GET)
    @ResponseBody
    public MessageResult reCreateTask(@RequestParam Integer boardid){
        //当前时间
        //Date currentTime = new Date();
        String date = DateUtil.getDateLast(1);
        //String currentTimeStr = DateUtil.format(currentTime,"yyyy-MM-dd");
        //删除bardroom的任务（当前日期之后的所有已生成的任务）
        EntityWrapper<Normal> normalEntityWrapper = new EntityWrapper<>();
        normalEntityWrapper.ge("createtime",date);
        normalEntityWrapper.eq("boardid",boardid);
        normalService.delete(normalEntityWrapper);
        //删除已更新到Task的任务
        EntityWrapper<Task> taskEntityWrapper = new EntityWrapper<>();
        taskEntityWrapper.ge("createtime",date);
        taskEntityWrapper.eq("boardid",boardid);
        taskEntityWrapper.lt("status",20);
        taskService.delete(taskEntityWrapper);
        //获取需要修改的变电站
        Boardroom boardroom = boardroomService.selectById(boardid);
        //根据日期重新生成Noraml任务
        try {
            //获取定时检查日期 50
            Date checktime = boardroom.getChecktime();
            //红外测温日期60
            Date hwcwtime = boardroom.getHwcwtime();
            //开关核对70
            Date kghdtime = boardroom.getKghdtime();
            //设备清扫40
            Date sbqstime = boardroom.getSbqstime();
            //环境清扫80
            Date hjqstime = boardroom.getHjqstime();
            Date tgtime = boardroom.getStoptime();
            if (checktime != null && tgtime!=null) {
                //50
                List<TaskType> listdsxj = getListDate(checktime, tgtime, "50");
                addTask(listdsxj, boardroom);
            }
            if (hwcwtime != null && tgtime!=null) {
                //60
                List<TaskType> listhwcw = getListDate(hwcwtime, tgtime, "60");
                addTask(listhwcw, boardroom);
            }
            if (kghdtime != null && tgtime!=null) {
                //70
                List<TaskType> listkghd = getListDate(kghdtime, tgtime, "70");
                addTask(listkghd, boardroom);
            }
            if (sbqstime != null && tgtime!=null) {
                //40
                List<TaskType> listsbqs = getListDate(sbqstime, tgtime, "40");
                addTask(listsbqs, boardroom);
            }
            if (hjqstime != null && tgtime!=null) {
                //80
                List<TaskType> listhjqs = getListDate(hjqstime, tgtime, "80");
                addTask(listhjqs, boardroom);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //将任务更到Task
        normalService.updateStatus();
        return MessageResult.getSuccess("更新任务成功!");
    }

    private void addTask(List<TaskType> listckDate,Boardroom bean){
        for(TaskType taskType: listckDate){
            Date starttime = taskType.getTime();
            Normal task = new Normal();
            //如果存在任务跳过
            EntityWrapper<Normal> normalEntityWrapper = new EntityWrapper<>();
            normalEntityWrapper.eq("boardid",bean.getId());
            normalEntityWrapper.eq("createtime",DateUtil.format(starttime));
            //normalEntityWrapper.eq("starttime",DateUtil.format(starttime));
            normalEntityWrapper.eq("tasktype",taskType.getType());
            List<Normal> listNormal = normalService.selectList(normalEntityWrapper);
            if(listNormal==null || listNormal.size()<=0) {
                //50代表日常巡视
                task.setTasktype(Integer.parseInt(taskType.getType()));
                task.setBoardname(bean.getBoardname());
                task.setBoardid(bean.getId());
                task.setBoardlat(bean.getBoardlat());
                task.setBoardlng(bean.getBoardlng());
                task.setCreatetime(starttime);
                task.setProjectid(bean.getProjectid());
                task.setProjectname(bean.getProjectname());
                task.setProjectcode(bean.getProjectcode());
                task.setVoltmark(bean.getVoltmark());
                task.setVolume(bean.getVolume());
                //巡检单位
                task.setRouterid(bean.getRouterid());
                task.setRoutername(bean.getRoutername());
                //查询巡检人员
                EntityWrapper<Cunsumer> cunsumerEntityWrapper = new EntityWrapper<>();
                cunsumerEntityWrapper.eq("routerid",bean.getRouterid());
                cunsumerEntityWrapper.eq("leader",1);
                List<Cunsumer> listc = cunsumerService.selectList(cunsumerEntityWrapper);
                Cunsumer cunsumer = listc.get(0);
                task.setCunsumerid(cunsumer.getId());
                task.setCunsumername(cunsumer.getName());
                task.setCunsumermobile(cunsumer.getMobile());

                task.setFactoryname(bean.getFactoryname());
                task.setFactoryphone(bean.getFactoryphone());
                task.setFactoryuser(bean.getFactoryuser());

                task.setUsertype("-");
                //暂不启用
                task.setStatus(0);
                task.setTaskdate(DateUtil.format(starttime,"yyyyMM"));
                try{
                    normalService.insert(task);
                }catch (Exception e){
                    //System.out.println("插入失败："+task);
                }

            }else{
            }
        }
    }

    private List<TaskType> getListDate(Date start, Date end, String type){
        List<TaskType> listDate = new ArrayList<>();
        String rr = DateUtil.format(start,"dd");

        Calendar tempStart = Calendar.getInstance();
        tempStart.setTime(new Date());

        Calendar tempEnd = Calendar.getInstance();
        tempEnd.setTime(end);
        tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
        while (tempStart.before(tempEnd)) {
            //处理2月没有30号的问题
            if(DateUtil.format(tempStart.getTime(),"MM").equals("02")) {
                if(rr.equals("29")||rr.equals("30")||rr.equals("31")) {
                    if("28".equals(DateUtil.format(tempStart.getTime(), "dd"))) {
                        listDate.add(new TaskType(tempStart.getTime(),type));
                    }
                }else{
                    if (DateUtil.format(start, "dd").equals(DateUtil.format(tempStart.getTime(), "dd"))) {
                        listDate.add(new TaskType(tempStart.getTime(),type));
                    }
                }
                //处理月大月小的问题
            }else if(DateUtil.format(tempStart.getTime(),"MM").equals("04")||
                    DateUtil.format(tempStart.getTime(),"MM").equals("06")||
                    DateUtil.format(tempStart.getTime(),"MM").equals("09")||
                    DateUtil.format(tempStart.getTime(),"MM").equals("11")) {
                if(rr.equals("31")) {
                    if("30".equals(DateUtil.format(tempStart.getTime(), "dd"))) {
                        listDate.add(new TaskType(tempStart.getTime(),type));
                    }
                }else{
                    if (DateUtil.format(start, "dd").equals(DateUtil.format(tempStart.getTime(), "dd"))) {
                        listDate.add(new TaskType(tempStart.getTime(),type));
                    }
                }

            }else{
                if (DateUtil.format(start, "dd").equals(DateUtil.format(tempStart.getTime(), "dd"))) {
                    listDate.add(new TaskType(tempStart.getTime(),type));
                }
            }
            tempStart.add(Calendar.DAY_OF_YEAR, 1);
        }
        return listDate;
    }

    class TaskType{
        private Date time;
        private String type;

        public TaskType(Date time, String type) {
            this.time = time;
            this.type = type;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public Date getTime() {
            return time;
        }

        public void setTime(Date time) {
            this.time = time;
        }

        @Override
        public String toString() {
            return "TaskType{" +
                    "time=" + DateUtil.format(time) +
                    ", type='" + type + '\'' +
                    '}';
        }
    }
}

